package com.ejlchina.tool.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentIndexFixStepTwoBinding
import com.ejlchina.tool.adapter.DeviceHeadAdapterIndexFix
import com.ejlchina.tool.adapter.DeviceHeadAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.constant.REQUEST_QR_SCAN_KEY
import com.ejlchina.tool.extension.safeNavigate
import com.ejlchina.tool.network.BucketIndexUpdateReqBean
import com.ejlchina.tool.network.NetApi
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.singleton.GlobalParams
import com.ejlchina.tool.util.COMMAND_485_SLAVE_SET_DOWNLOAD
import com.ejlchina.tool.util.Executor
import com.ejlchina.tool.util.bytearray.intToByteHexString
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.view.GridItemDecoration
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

const val BUNDLE_QR_SCAN = "BUNDLE_QR_SCAN"
const val BUNDLE_INDEX_FIX_FAIL_LIST = "BUNDLE_INDEX_FIX_FAIL_LIST"
class IndexFixStepTwoFragment: BaseBindingFragment2<FragmentIndexFixStepTwoBinding>() {

    private val deviceListIndexFixTwo = arrayListOf<BleDeviceBean>()
    private lateinit var deviceListHeadAdapter: DeviceHeadAdapterIndexFix

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        initListeners()
    }

    private fun initData(){
        if (deviceListIndexFixTwo.isEmpty()){
            arguments?.getParcelableArrayList<BleDeviceBean>(BUNDLE_DEVICE_LIST)?.let { deviceListIndexFixTwo.addAll(it) }
        }
        setDeviceData()

    }

    private fun setDeviceData(){
        deviceListHeadAdapter = DeviceHeadAdapterIndexFix(deviceListIndexFixTwo)
        binding.rvDevices.apply {
            adapter = deviceListHeadAdapter
            layoutManager = GridLayoutManager(requireContext(),2)
            if (itemDecorationCount == 0){
                addItemDecoration(GridItemDecoration(2,11,11))
            }
        }
    }

    private fun initListeners(){

        binding.ivScan.setOnClickListener {
            findNavController().safeNavigate(R.id.action_index_fix_to_scan)
        }

        requireActivity().supportFragmentManager.setFragmentResultListener(REQUEST_QR_SCAN_KEY, this){ _, bundle ->
            val result = bundle.getString(BUNDLE_QR_SCAN)
            binding.tvScan.text = result
        }

        binding.btnConfirm.setOnClickListener {
            updateBucketIndexInfo()
        }
    }

    private fun updateBucketIndexInfo(){
        showLoading()
        val bucketIndexUpdateReqList = arrayListOf<BucketIndexUpdateReqBean>()
        val selectDeviceList = deviceListIndexFixTwo.filter { it.isSelect }
        for (item in selectDeviceList){
            val bucketIndexUpdateReqBean = BucketIndexUpdateReqBean()
            bucketIndexUpdateReqBean.mac = item.bleDevice.mac
            bucketIndexUpdateReqBean.bucketNo = item.bucketNo.toString()
            for (versionItem in GlobalParams.connectDeviceVersionList){
                if (versionItem.mac == bucketIndexUpdateReqBean.mac){
                    bucketIndexUpdateReqBean.firmwareVer = versionItem.firmwareVersion
                    bucketIndexUpdateReqBean.hardwareVer = versionItem.hardVersion
                }
            }
            bucketIndexUpdateReqList.add(bucketIndexUpdateReqBean)
        }
        NetApi.updateBuckets(binding.tvScan.text.toString(),bucketIndexUpdateReqList){ indexFixUpdateFailBeanList ->

            Executor.runOnMain{
                if (indexFixUpdateFailBeanList != null){
                    if (indexFixUpdateFailBeanList.isNotEmpty()){
                        val bundle = bundleOf(BUNDLE_INDEX_FIX_FAIL_LIST to indexFixUpdateFailBeanList.toMutableList())
                        findNavController().navigate(R.id.action_index_fix_to_fail_dialog, bundle)
                    }else {
                        updateIndexFixData()
                        set485SlaveCommandData()
                        showToast("标定成功")
                    }
                }else{
                    dismissLoading()
                    showToast("标定失败")
                }
            }
        }
    }

    private fun updateIndexFixData(){
        deviceListIndexFixTwo.filter { it.isSelect }.forEach { fixIndexDevice ->
            GlobalConnectObject.getCurrentConnectDeviceList().find { it.bleDevice.mac == fixIndexDevice.bleDevice.mac }?.let { device ->
                device.bucketNo = fixIndexDevice.bucketNo
                device.deviceNo = fixIndexDevice.deviceNo
            }
        }
    }

    private fun set485SlaveCommandData(){
        viewLifecycleOwner.lifecycleScope.launch {
            for (item in deviceListIndexFixTwo.filter { it.isSelect }) {
                val addressData = intToByteHexString(79 + item.bucketNo)
                setCommandData(item, COMMAND_485_SLAVE_SET_DOWNLOAD,addressData)
                delay(900)
            }
            dismissLoading()
        }
    }
    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentIndexFixStepTwoBinding {
        return FragmentIndexFixStepTwoBinding.inflate(inflater,container,true)
    }
}